package com.wokeMy.view.channe.ronghui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.woke.data.UnionPayChannel;
import com.woke.httpupload.FileProviderUtils;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import cn.sharesdk.onekeyshare.OnekeyShare;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class RhuiZwmActivity extends BaseActivity implements View.OnClickListener,EasyPermissions.PermissionCallbacks{
    ImageView back_rhzwm_iv,zwm_rhzwm_iv;
    TextView share_rhui_zwm,title_rhui_zwm,zwmtitle_rhui_zwm;
    LinearLayout save_rhui_zwm;
    UnionPayChannel unionPayChannel;

    String user_id;
    int way_id;
    float amount;
    String flag,vip_level,ewmFile;
    int payWay;

    Bitmap cachebmp;
    Dialog dialog;
    @Override
    public void setContentView() {
        setContentView(R.layout.activity_rhui_zwm);
    }

    @Override
    public void initActivity() {
        back_rhzwm_iv.setOnClickListener(this);
        share_rhui_zwm.setOnClickListener(this);
        save_rhui_zwm.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                aralogid("确定保存二维码到相册");


                return true;
            }
        });
        dialog= Util.createLoadingDialog(RhuiZwmActivity.this);
        switch (flag) {
            case "rhzwm":
                // 融汇银联 二维码
                openRhGood();
                break;
            case "fmZfbZwm":
                // 富民  二维码
                title_rhui_zwm.setText("支付宝二维码");
                save_rhui_zwm.setBackgroundResource(R.mipmap.alipay_backgroud);
                zwmtitle_rhui_zwm.setVisibility(View.GONE);
                fmZfbZwm();
                break;
            case "zqfmzfb":
                // 直清富民  二维码
                title_rhui_zwm.setText("支付宝二维码");
                save_rhui_zwm.setBackgroundResource(R.mipmap.alipay_backgroud);
                zwmtitle_rhui_zwm.setVisibility(View.GONE);
                zqEwm();
                break;
            case "zqfmwx":
                // 富民 二维码
                title_rhui_zwm.setText("微信二维码");
                save_rhui_zwm.setBackgroundResource(R.mipmap.wechat_background);
                zwmtitle_rhui_zwm.setVisibility(View.GONE);
                zqEwm();
                break;
            case "fmwxZwm":
                // 富民 二维码
                title_rhui_zwm.setText("微信二维码");
                save_rhui_zwm.setBackgroundResource(R.mipmap.wechat_background);
                zwmtitle_rhui_zwm.setVisibility(View.GONE);
                fmZfbZwm();
                break;
            default:
                break;
        }

    }

    @Override
    public void initView() {
        title_rhui_zwm= myFindViewById(R.id.title_rhui_zwm);
        back_rhzwm_iv= myFindViewById(R.id.back_rhzwm_iv);
        share_rhui_zwm= myFindViewById(R.id.share_rhui_zwm);
        zwm_rhzwm_iv= myFindViewById(R.id.zwm_rhzwm_iv);
        save_rhui_zwm= myFindViewById(R.id.save_rhui_zwm);
        zwmtitle_rhui_zwm= myFindViewById(R.id.zwmtitle_rhui_zwm);

    }

    @Override
    public void initData() {
        MyApp myApp=(MyApp)getApplication();
        Intent intent=getIntent();
        Datas_load datas_load=myApp.getDatas_load();
        user_id=datas_load.getId();
        vip_level=datas_load.getUser_type();
        unionPayChannel = (UnionPayChannel)(intent.getSerializableExtra("UnionPayChannel"));
        amount=intent.getFloatExtra ("money", 0.01f);
        flag=intent.getStringExtra("flag");
        Log.e("unionPayChannel",unionPayChannel.toString());
        way_id=unionPayChannel.getWay();
        payWay=unionPayChannel.getKind();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_rhzwm_iv:
                finish();
                break;
            case R.id.share_rhui_zwm:
                showShare();
                break;
            default:
                break;
        }
    }
    // 北京融汇商户（银联二维码）产品开通
    public void  openRhGood(){
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",user_id);
        params.put("way",way_id);
        params.put("productType","UnionPay"); //银联二维码
        //开通无卡快捷支付
        //        params.put("creditCardNo","6225757545273378");

        Log.e("北京融汇商户（银联二维码）产品开通params",params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.OPENGOOD_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String result = null;
                try {
                    result = new String(bytes, "utf-8");
                    //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                    Log.e("北京融汇商户（银联二维码）产品开通", result);
                    try {
                        JSONObject jsonObject=new JSONObject(result);
                        String respcode=jsonObject.getJSONObject("data").getJSONObject("data").getString("respcode");
                        if (respcode.equals("0000")){
                            requestEwm();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(dialog);
            }
        });
    }
    // 北京融汇银联二维码接口
    public void  requestEwm(){
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",user_id);
        params.put("way",way_id);
        params.put("payWay","3");//1.支付宝 2.微信 3。银联
        params.put("amount",amount);
        params.put("goodsName","中财在线产品");
        params.put("orderIp",Util.getIPAddress(RhuiZwmActivity.this));
        Log.e("北京融汇银联二维码接口params",params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.RHZWM_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Util.closeDialog(dialog);
                String result = null;
                try {
                    result = new String(bytes, "utf-8");
                    //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                    Log.e("北京融汇银联二维码接口", result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getString("flag").equals("success")){
                            createEnglishQRCode(jsonObject.getJSONObject("data").getString("data"));
                        }else {
                            if (!(jsonObject.getJSONObject("data").getJSONObject("data").getString("retmsg")==null)){
                                Toast.makeText(RhuiZwmActivity.this,jsonObject.getJSONObject("data").getJSONObject("data").getString("retmsg"),Toast.LENGTH_SHORT).show();

                            }else {

                                Toast.makeText(RhuiZwmActivity.this,jsonObject.getString("info"),Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(dialog);
            }
        });
    }
    private void createEnglishQRCode(final  String string) {
        /*
        这里为了偷懒，就没有处理匿名 AsyncTask 内部类导致 Activity 泄漏的问题
        请开发在使用时自行处理匿名内部类导致Activity内存泄漏的问题，处理方式可参考 https://github.com/GeniusVJR/LearningNotes/blob/master/Part1/Android/Android%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E6%80%BB%E7%BB%93.md
         */
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... params) {
                return QRCodeEncoder.syncEncodeQRCode(string, BGAQRCodeUtil.dp2px(RhuiZwmActivity.this, 150), Color.parseColor("#000000"));
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                    zwm_rhzwm_iv.setImageBitmap(bitmap);
                } else {
                    Toast.makeText(RhuiZwmActivity.this, "生成二维码失败", Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }
    private static final int READ_AND_WRITE_STORE = 88;

    @AfterPermissionGranted(READ_AND_WRITE_STORE)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions (this, perms)) {
            // Already have permission, do the thing
            Log.e ("MainActivity", "已经获得读写本地文件的权限");
            viewSaveToImage (save_rhui_zwm);
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions (this, "需要读写手机存储权限",
                    READ_AND_WRITE_STORE, perms);
        }
    }





    public void viewSaveToImage(View view) {
        boolean isOk = false;
        view.setDrawingCacheEnabled (true);
        view.setDrawingCacheQuality (View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor (Color.WHITE);

        // 把一个View转换成图片
     cachebmp = loadBitmapFromView (view);

        FileOutputStream fos = null;
        final File file = FileProviderUtils.createImageFile (this);
        if (file != null) {
            try {
                fos = new FileOutputStream (file);
                cachebmp.compress (Bitmap.CompressFormat.PNG, 90, fos);

                fos.flush ();
                fos.close ();
                ewmFile=file.getPath ();
                runOnUiThread (new Runnable () {
                    @Override
                    public void run() {
                        Toast.makeText (RhuiZwmActivity.this, "二维码保存成功" + file.getPath (), Toast.LENGTH_LONG)
                                .show ();
                    }
                });

                try {
                    String path = MediaStore.Images.Media.insertImage (getContentResolver (), file.getAbsolutePath (), "1_shoukuanma.png", "我的收款码");
                    Intent intent2 = new Intent (Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile (new File (path)));
                    intent2.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    sendBroadcast (intent2);

                    Intent intent = new Intent (Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile (new File (path)));
                    intent.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    sendBroadcast (intent);
                } catch (FileNotFoundException e) {
                    e.printStackTrace ();
                }

            } catch (Exception e) {
                e.printStackTrace ();
            }


        }
        view.setDrawingCacheEnabled (false);

    }
    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth ();
        int h = v.getHeight ();

        Bitmap bmp = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas (bmp);

        c.drawColor (Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.draw (c);

        return bmp;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult (requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == READ_AND_WRITE_STORE) {
            viewSaveToImage (save_rhui_zwm);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == READ_AND_WRITE_STORE) {
            new AlertDialog.Builder (this).setMessage ("请在<权限管理>里打开读写手机存储权限")
                    .setPositiveButton ("前往", new DialogInterface.OnClickListener () {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent (Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData (Uri.fromParts ("package", getPackageName (), null));
                            startActivity (intent);
                            dialog.dismiss ();
                        }
                    })
                    .setNegativeButton ("取消", null)
                    .create ()
                    .show ();
        }
    }
    AlertDialog alertDialog;
    private void aralogid(String info) {
        alertDialog = new AlertDialog.Builder(RhuiZwmActivity.this).
                setTitle(info).
//                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            methodRequiresTwoPermission ();
                        } else {
                            viewSaveToImage (save_rhui_zwm);
                        }
                    }
                }).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }
    //富民扫码充值 (支付宝or微信)
    public void  fmZfbZwm() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id", user_id);
        params.put("way", way_id); //区分支付宝 微信
        params.put("amount", amount);
        params.put("vip_level", vip_level);
        Log.e("富民扫码充值(支付宝or微信)params", params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.FMZFBEWM_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Util.closeDialog(dialog);
                String result = null;
                try {
                    result = new String(bytes, "utf-8");
                    //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                    Log.e("富民扫码充值(支付宝or微信)", result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getString("flag").equals("success")) {
                            createEnglishQRCode(jsonObject.getJSONObject("data").getString("data"));
                        } else {
                            if (!(jsonObject.getJSONObject("data").getJSONObject("data").getString("retmsg") == null)) {
                                Toast.makeText(RhuiZwmActivity.this, jsonObject.getJSONObject("data").getJSONObject("data").getString("retmsg"), Toast.LENGTH_SHORT).show();

                            } else {

                                Toast.makeText(RhuiZwmActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(dialog);
            }
        });
    }
    //直清富民扫码充值 (支付宝or微信)
    public void  zqEwm() {
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id", user_id);
        params.put("way", way_id); //区分支付宝 微信
        params.put("amount", amount);
        Log.e("直清富民扫码充值(支付宝or微信)params", params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.FMZQZWM_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Util.closeDialog(dialog);
                String result = null;
                try {
                    result = new String(bytes, "utf-8");
                    //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                    Log.e("直清富民扫码充值(支付宝or微信)", result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.getString("flag").equals("success")) {
                            createEnglishQRCode(jsonObject.getJSONObject("data").getString("data"));
                        } else {
                            if (!(jsonObject.getJSONObject("data").getJSONObject("data").getString("retmsg") == null)) {
                                Toast.makeText(RhuiZwmActivity.this, jsonObject.getJSONObject("data").getJSONObject("data").getString("retmsg"), Toast.LENGTH_SHORT).show();

                            } else {

                                Toast.makeText(RhuiZwmActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(dialog);
            }
        });
    }

    private void showShare() {
//        ShareSDK.initSDK (this);
        OnekeyShare oks = new OnekeyShare ();
        // �ο����������½ڣ����÷������
        // ����һ��ͼ��
//        Bitmap enableLogo = BitmapFactory.decodeResource (getResources (), R.drawable.ssdk_oks_logo_fuzhi);
//        String label = "复制链接";
//        View.OnClickListener listener = new View.OnClickListener() {
//            public void onClick(View v) {
////                myClip = ClipData.newPlainText ("text", getResources().getString(R.string.oem_friend_tuijian));
////                myClipboard.setPrimaryClip (myClip);
////                Toast.makeText (getApplicationContext (), "已复制到剪贴板",
////                        Toast.LENGTH_SHORT).show ();
//            }
//        };
//        oks.setTheme (OnekeyShareTheme.CLASSIC);
//
//        oks.disableSSOWhenAuthorize ();
//        oks.setCustomerLogo (enableLogo, label, listener);

//        oks.setTitle (getResources().getString(R.string.oem_title_tuijian_share));
//        oks.setText (getResources().getString(R.string.oem_content_tuijian_share));
       if (flag.equals("rhzwm")){
           oks.setViewToShare(zwm_rhzwm_iv);
       }else {
           oks.setViewToShare(save_rhui_zwm);
       }
        //        oks.setComment (getResources ().getString (R.string.app_name));
//        oks.setSite (getResources().getString(R.string.oem_title_tuijian_share));
        oks.setVenueName (getResources ().getString (R.string.app_name));

        // ��������GUI
        oks.show (this);
    }
}
